const mongoose = require('mongoose')
const roleModel = require('../model/roleModel')

//在数据库中创建一个新角色
const createRole = async(roleInfo)=>{
    let {name,region,starLevel,element,weapon,imageUrl} = roleInfo

    try {
        let result = await roleModel.create({
            name,
            region,
            starLevel,
            element,
            weapon,
            imageUrl
        })

        return result
    } catch (error) {
        return Promise.reject('创建失败')
    }
}

//依据条件conditions，在数据库查找对应角色
const findRoles = async(conditions={})=>{
    // console.log(conditions)
    Object.keys(conditions).forEach((key)=>{
        if(conditions[key] == '不限'){
            delete conditions[key]
        }
    })
    // console.log(conditions) 
    try {
        let result = await roleModel.find(conditions)
        return result
    } catch (error) {
        return Promise.reject('查询失败')
    }
    
}

//依据_id，删除指定角色信息
const deleteARole = async(_id)=>{
    try{
        await roleModel.findByIdAndDelete(_id)
        return '删除成功'
    }catch (error){
        return Promise.reject('删除失败')
    }
}

//根据_id，更新角色信息
const updateRoleInfo = async(_id,updateInfo)=>{
    try{
        await roleModel.findByIdAndUpdate(_id,{ $set: JSON.parse(updateInfo)})
        return "更新成功"
    }catch(error){
        console.log(error);
        return Promise.reject('更新失败')
    }
}

//返回符合分页条件的角色信息 pageNo:当前页码 pageSize:一页展示的数量 total:总数量
//limit -- pageSize skip -- (pageNo-1)*pageSize 
const findRolesWithinLimits = async(pageNo,pageSize)=>{
    let limit = parseInt(pageSize)
    let skip = (parseInt(pageNo)-1)*limit
    let result = {}
    
    try {
        let roleInfoArr = await roleModel.find({},null,{skip,limit})
        let total = (await roleModel.find({})).length
        result.roleInfoArr = roleInfoArr
        result.total = total
        return result
    } catch (error) {
        console.log(error);
        return Promise.reject('查询失败')
    }
    
}

module.exports = {
    createRole,
    findRoles,
    deleteARole,
    updateRoleInfo,
    findRolesWithinLimits
}
